package org.durcframework.autocode.generator.oracle;

import java.util.Map;
import java.util.Set;

import org.durcframework.autocode.generator.ColumnDefinition;
import org.durcframework.autocode.generator.ColumnSelector;
import org.durcframework.autocode.generator.DataBaseConfig;
import org.springframework.util.StringUtils;

/**
 * mysql表信息查询
 *
 */
public class OracleColumnSelector extends ColumnSelector {
	
	public OracleColumnSelector(DataBaseConfig dataBaseConfig) {
		super(dataBaseConfig);
	}

	/**
	 * SHOW FULL COLUMNS FROM 表名
	 */
	@Override
	protected String getColumnInfoSQL(String tableName) {
		StringBuffer sql=new StringBuffer();
		sql.append(" select t.*,p.key,c.comments from (");
			//查询字段信息
			sql.append(" select COLUMN_NAME FILED,DATA_TYPE TYPE,DATA_LENGTH LENGTH,NULLABLE NUL  from user_tab_columns  where table_name='" );
			sql.append(tableName);
			//查询主键
			sql.append("') t left join (select 'PRI' key ,a.constraint_name,  a.column_name from user_cons_columns a, user_constraints b ");
								sql.append(" where a.constraint_name = b.constraint_name and b.constraint_type = 'P' and a.table_name = '" );
								sql.append(tableName);
		sql.append("') p on p.column_name=t.filed");
		//查询注释
		sql.append(" left join (select column_name,comments from user_col_comments  where Table_name='S_USER') c on t.filed=c.column_name" );
		
		
		return sql.toString();
	}
	
	/*
	 * {FIELD=username, EXTRA=, COMMENT=用户名, COLLATION=utf8_general_ci, PRIVILEGES=select,insert,update,references, KEY=PRI, NULL=NO, DEFAULT=null, TYPE=varchar(20)}
	 */
	protected ColumnDefinition buildColumnDefinition(Map<String, Object> rowMap){
		Set<String> columnSet = rowMap.keySet();
		
		for (String columnInfo : columnSet) {
			rowMap.put(columnInfo.toUpperCase(), rowMap.get(columnInfo));
		}
		ColumnDefinition columnDefinition = new ColumnDefinition();
		columnDefinition.setColumnName((String)rowMap.get("FILED"));
		boolean isIdentity = "auto_increment".equalsIgnoreCase(String.valueOf(rowMap.get("EXTRA")));
		columnDefinition.setIsIdentity(isIdentity);
		boolean isPk = "PRI".equalsIgnoreCase((String)rowMap.get("KEY"));
		columnDefinition.setIsPk(isPk);
		String type = (String)rowMap.get("TYPE");
		columnDefinition.setType(type);
		columnDefinition.setComment((String)rowMap.get("COMMENTS"));
		return columnDefinition;
	}
	
}
